package com.woniu.service.impl;

import com.woniu.entity.vo.MenuVo;
import com.woniu.mapper.CtfMenuMapper;
import com.woniu.service.CtfMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @Author hq
 * @Date 2025/6/14$ 22:52$
 * @Description TODO
 * @Params $
 * @Return $
 **/
@Service
public class CtfMenuServiceImpl implements CtfMenuService {
    @Autowired
    private CtfMenuMapper menuMapper;
    /**
     * 查询二级菜单
     */
    @Override
    public List<MenuVo> selectMenuList() {
        return buildMenuTree(menuMapper.selectAllMenus());
    }

    private List<MenuVo> buildMenuTree(List<MenuVo> menus) {
        Map<Integer, MenuVo> menuMap = menus.stream()
                .collect(Collectors.toMap(MenuVo::getMenuId, Function.identity()));

        List<MenuVo> result = new ArrayList<>();
        for (MenuVo menu : menus) {
            Integer parentId = menu.getParentId();
            if (parentId == null || parentId == 0) {
                result.add(menu);
            } else {
                MenuVo parent = menuMap.get(parentId);
                if (parent != null) {
                    parent.getChildren().add(menu);
                }
            }
        }
        return result;
    }

    /**
     * 根据id删除菜单，如果是父菜单，则一起删除子菜单
     * @param id
     */
    @Override
    public void deleteById(Integer id) {
        menuMapper.deleteById(id);
    }
}
